import { useEffect, useState, Fragment } from 'react'
import { useNavigate } from 'react-router-dom';
import { Table, Space, Tooltip, Button, Modal, message, Tree } from 'antd'
import { DeleteOutlined, UnorderedListOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { http } from '@/utils/http';
const { confirm } = Modal;

export default function RoleList() {
  const navigate = useNavigate()
  const [roleList, setRoleList] = useState([])  // 角色列表数据
  const [rightList, setRightList] = useState([])  // 权限树形数据
  const [tableLoading, setTableLoading] = useState(false)  // table组件是否处于loading状态
  const [currentRights, setCurrentRights] = useState([])  // 角色对应的权限数据
  const [currentId, setCurrentId] = useState(0)  // 当前修改的角色ID

  const getRoleList = async () => {
    const { data } = await http.get('/roles')
    setRoleList(data)
  }
  const getRightList = async () => {
    const { data } = await http.get('/rights?_embed=children')
    setRightList(data)
  }

  useEffect(() => {
    getRoleList()
    getRightList()
  }, [])

  // 展示删除确认框
  const showConfirm = item => {
    confirm({
      title: '确定要删除该角色吗？',
      icon: <ExclamationCircleOutlined />,

      onOk() {
        deleteConfirm(item)
      },

      onCancel() {
        message.info('您取消了该操作！', 2)
      },
    });
  }

  // 确定删除角色
  const deleteConfirm = item => {
    setTableLoading(true)
    setRoleList(roleList.filter(data => data.id !== item.id))
    http.delete(`/roles/${item.id}`).then(() => setTableLoading(false))
    message.success('您删除了该角色！', 2)
  }

  // 树形控件弹出框显示与否
  const [isModalVisible, setIsModalVisible] = useState(false)

  // 点击Tree的复选框的回调
  const onCheck = checkedKeys => {
    setCurrentRights(checkedKeys)
  }

  // 点击Tree节点的回调
  const handleSelect = key => {  // 拿到点击的key值
    const typeCurrent = Array.isArray(currentRights) // currentRights是数组，返回true；是对象，返回false
    if (typeCurrent) {
      if (currentRights.includes(key)) {
        const formatCurrent = [...currentRights]
        formatCurrent.splice(formatCurrent.indexOf(key), 1)
        setCurrentRights(formatCurrent)
      } else {
        const formatCurrent = [...currentRights]
        formatCurrent.push(key)
        setCurrentRights(formatCurrent)
      }
    } else {
      if (currentRights.checked.includes(key)) {
        const formatCurrent = [...currentRights.checked]
        formatCurrent.splice(formatCurrent.indexOf(key), 1)
        setCurrentRights(formatCurrent)
      } else {
        const formatCurrent = [...currentRights.checked]
        formatCurrent.push(key)
        setCurrentRights(formatCurrent)
      }
    }
  }

  // 弹出框点击确定按钮的回调
  const modalOk = () => {
    console.log(currentRights)
    console.log(currentId)
    setIsModalVisible(false)
    // 修改对应角色的权限
    setRoleList(roleList.map(item => {
      if (item.id === currentId) {
        return {
          ...item,
          rights: currentRights
        }
      }
      return item
    }))
    // 发起请求 同步后端(patch)
    http.patch(`/roles/${currentId}`, {
      rights: currentRights
    }).then(() => {
      message.success('更新权限成功！', 2)
      // 更新token中的权限
      const newsToken = JSON.parse(window.sessionStorage.getItem('news'))
      if (currentId === newsToken.roleId) {
        window.sessionStorage.removeItem('news')
        window.sessionStorage.setItem('news', JSON.stringify({
          ...newsToken,
          role: {
            id: newsToken.role.id,
            rights: currentRights,
            roleName: newsToken.role.roleName,
            roleType: newsToken.role.roleType
          }
        }))
        navigate(0)
      }
    })
      .catch(() => message.error('更新权限失败！', 2))
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      render: id => {
        return <b>{id}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      align: 'center'
    },
    {
      title: '操作',
      align: 'center',
      render: item => {
        return (
          <Space>
            <Tooltip title="delete" placement="left">
              <Button danger type="primary" shape="circle" icon={<DeleteOutlined />}
                onClick={() => showConfirm(item)} disabled={item.id === 1 ? true : false} />
            </Tooltip>
            <Tooltip title="edit" placement="right">
              <Button type="primary" shape="circle" icon={<UnorderedListOutlined />}
                onClick={() => {
                  setIsModalVisible(true)
                  setCurrentRights(item.rights)
                  setCurrentId(item.id)
                }} />
            </Tooltip>
          </Space>
        )
      }
    },
  ];

  return (
    <Fragment>
      <Table dataSource={roleList} columns={columns} rowKey={item => item.id} loading={tableLoading} />
      <Modal title="权限分配" visible={isModalVisible} onOk={() => modalOk()}
        onCancel={() => {
          setIsModalVisible(false)
          message.info('您取消了权限分配！', 2)
        }}
        destroyOnClose>
        <Tree
          checkable
          treeData={rightList}
          checkedKeys={currentRights}
          onCheck={checkedKeys => onCheck(checkedKeys)}
          onSelect={(_, { node: { key } }) => handleSelect(key)}
          checkStrictly
        />
      </Modal>
    </Fragment>
  )
}